package org.forex.impl.engine;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.forex.impl.ws.DeleteOrder;
import org.forex.impl.ws.GetInstruments;
import org.forex.impl.ws.GetTrades;
import org.forex.vo.Instruments;
import org.forex.vo.Order;
import org.forex.vo.Trades;

import com.google.gson.Gson;

@WebListener
public class Engine implements ServletContextListener{

	CheckInstruments cins;
	ScheduledExecutorService sched=Executors.newScheduledThreadPool(1);
	
	String[] markets=new String[]{"AU200_AUD","CH20_CHF","DE30_EUR","EU50_EUR","DE10YB_EUR","FR40_EUR","HK33_HKD",
								"JP225_USD","NAS100_USD","NL25_EUR","SG30_SGD","SOYBN_USD","SPX500_USD","UK100_GBP",
								"UK10YB_GBP","US2000_USD","US30_USD","USB02Y_USD","USB05Y_USD","USB10Y_USD","USB30Y_USD"
							};
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		
		cins.shutdown();
		
		if(!sched.isShutdown())
			sched.shutdownNow();
		
		//cancello tutti i trade
//		Trades trades;
//		try {
//			trades = new GetTrades().get();
//			Order order=new Order();
//			trades.getTrades().forEach(tr->{
//				
//				order.setId(tr.getId());
//				try {
//					new DeleteOrder().delete(order);
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			});
//		} catch (IOException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
		
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		
//		Set<String> marketsSet=new HashSet<String>(Arrays.asList(markets));
//		
//		
//		try {
//			Gson gson=new Gson();
//			cins=new CheckInstruments();
//			
//			Instruments ins=new GetInstruments().getAll();
//			
//			ins.getInstruments().stream().filter(in->!marketsSet.contains(in.getInstrument()) && in.getDisplayName().startsWith("Gold/") && !in.getDisplayName().startsWith("Silver/")).forEach(in->{
//			//ins.getInstruments().forEach(in->{
//				System.out.println(gson.toJson(in));
//				cins.addCheckOrder(new CheckOrder(in));
//			});
//			
//			sched.scheduleAtFixedRate(cins, 0, 10, TimeUnit.SECONDS);
//			
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}		
	}

}
